/**
 * 所有服务类的公共类,其它服务类继承此类
 */
const fs = require("fs");
const AV = require("leanengine");
class BaseServ {
  constructor(moduleName, cnName) {
    this.moduleName = moduleName;
    this.cnName = cnName;
  }

  /**
   * 上传图片接口
   */
  async uploadIns(localFile) {
    const data = fs.createReadStream(localFile.file.path);
    const avFile = new AV.File(localFile.file.name, data);
    return avFile.save();
  }

  /**
   *
   * @param {名称} name
   */
  checkName(name) {
    return new Promise(async (resolve, reject) => {
      let query = new AV.Query(this.moduleName);
      query.equalTo("name", name);
      let result = await query.find();
      if (result.length > 0) {
        resolve({
          code: "202",
          msg: `${this.cnName || this.moduleName}名称已存在`
        });
      } else {
        resolve(false);
      }
    });
  }

  /**
   *
   * @param {名称} name
   */
  async checkNameIns(name) {
    return new Promise(async (resolve, reject) => {
      let query = new AV.Query(this.moduleName);
      query.equalTo("name", name);
      let count = await query.count();
      if (count > 0) {
        resolve({
          code: '101',
          msg: '影片已存在'
        })
      } else {
        resolve(false);
      }
    })
  }

  /**
   *
   * @param {*} attrs 需要校验的属性数组
   * @param {*} params 前端发来的参数
   */
  checkAttr(attrs, params) {
    // 查找没有值的属性
    let res = attrs.find(attr => {
      return params[attr] === undefined || params[attr] === "";
    });
    // 没有值的属性给出提示
    if (res) {
      return {
        code: "604",
        msg: `缺少${res}`
      };
    } else {
      return false;
    }
  }

  // 查找列表(所有)
  findListInterface(attrs) {
    const query = new AV.Query(this.moduleName);
    if (attrs && attrs.length > 0) {
      query.select(attrs);
    }
    return query.find();
  }

  // 添加
  addInterface(params) {
    // 创建一个实例
    const entry = new AV.Object(this.moduleName);
    // 添加对象里的所有属性
    for (let p in params) {
      entry.set(p, params[p]);
    }
    return entry.save();
  }
  // 更新
  updateInterface(params, id) {
    // 创建一个实例
    const entry = AV.Object.createWithoutData(this.moduleName, id);
    // 添加对象里的所有属性
    for (let p in params) {
      if (p.match("Id")) {
        continue;
      }
      try {
        entry.set(p, params[p]);
      } catch (error) {
        continue;
      }
    }
    return entry.save();
  }

  // 添加并关联到某个模块
  addAndDependent(params, dependentObj) {
    // 创建一个实例
    const entry = new AV.Object(this.moduleName);
    // 添加对象里的所有属性
    for (let p in this.attrs) {
      entry.set(p, params[p]);
    }
    entry.set("dependent", dependentObj);
    return entry.save();
  }

  // 根据id删除
  delInterfaceById(objectId) {
    console.log('objectId', objectId);
    try {
      let entry = AV.Object.createWithoutData(this.moduleName, objectId);
      return entry.destroy();
    } catch (error) {
      console.log(error);
      Promise.reject(error);
    }
  }

  // 根据id查询
  findInterfaceById(objectId) {
    const query = new AV.Query(this.moduleName);
    query.include("dependent");
    query.equalTo("objectId", objectId);
    return query.first();
  }

  formatDate(time) {
    let date = new Date(time);
    let M = date.getMonth() + 1;
    let D = date.getDate();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    M = M < 10 ? '0' + M : M;
    D = D < 10 ? '0' + D : D;
    h = h < 10 ? '0' + h : h;
    m = m < 10 ? '0' + m : m;
    s = s < 10 ? '0' + s : s;
    return `${M}-${D} ${h}:${m}:${s}`;
  }

  errInfo(error) {
    let {
      code,
      message
    } = error;
    let errObj = {
      '211': '用户不存在',
      '210': '用户名或密码错误'
    }
    message = errObj[code];

    let type = typeof error;
    if (type === "string") {
      code = 500;
      message = "服务器错误";
    }
    return {
      code: code,
      msg: message
    };
  }

  /**
   * 给数据添加成功和失败的对象
   * params@type 成功的查询1,失败的查询0
   */
  addResInfo({
    type,
    code,
    msg,
    result,
    error
  }) {
    if (type === 1 && !!result) {
      return {
        code: "666"
      };
    }
    if (type === 1 && !result) {
      return {
        code: 20001,
        msg
      };
    }

    // 以上为成功的处理,下面为失败的处理
    return {
      code: 500,
      ...error,
      msg
    };
  }
}

module.exports = BaseServ;
